<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="抓拍时间">
        <el-date-picker
          v-model="daterangeTime"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input
          v-model="queryParams.age"
          placeholder="请输入年龄"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.gender"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="IC卡号" prop="icCard">
        <el-input
          v-model="queryParams.icCard"
          placeholder="请输入IC卡号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工号" prop="workId">
        <el-input
          v-model="queryParams.workId"
          placeholder="请输入工号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="department">
        <el-input
          v-model="queryParams.department"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="人员类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择人员类别" clearable>
          <el-option
            v-for="dict in dict.type.category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['capture:capture:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['capture:capture:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="captureList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="抓拍时间" align="center" prop="time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.gender"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="IC卡号" align="center" prop="icCard" />
      <el-table-column label="工号" align="center" prop="workId" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="部门名称" align="center" prop="department" /> -->
      <el-table-column label="人员类别" align="center" prop="category">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.category2" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="识别相似度" align="center" prop="score" />
      <!-- <el-table-column label="身份证号" align="center" prop="idCard" /> -->
      <el-table-column label="人脸图路径" align="center" prop="jpegUrlFace" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.jpegUrlFace" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showDetail(scope.row)"
            v-hasPermi="['capture:capture:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['capture:capture:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="showAddPersonDialog(scope.row)"
            v-hasPermi="['person:person:add']"
          >入库</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人脸抓拍记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

<!-- 详情弹窗 - 栅格布局 -->
<el-dialog :title="'详情'" :visible.sync="detailDialogVisible" width="800px" append-to-body>
  <el-row :gutter="20">
    <!-- 左侧栏 -->
    <el-col :span="12">
      <el-descriptions v-if="detailData" :column="1" border>
        <!-- <el-descriptions-item label="序号">{{ detailData.id }}</el-descriptions-item> -->
        <el-descriptions-item label="抓拍时间">{{ detailData.time }}</el-descriptions-item>
        <el-descriptions-item label="设备序列号">{{ detailData.sn }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="年龄">{{ detailData.age }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <dict-tag :options="dict.type.gender" :value="detailData.gender"/>
        </el-descriptions-item>
        <el-descriptions-item label="IC卡号">{{ detailData.icCard }}</el-descriptions-item>
        <el-descriptions-item label="工号">{{ detailData.workId }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailData.phone }}</el-descriptions-item>
        <el-descriptions-item label="部门名称">{{ detailData.department }}</el-descriptions-item>
      </el-descriptions>
    </el-col>

    <!-- 右侧栏 -->
    <el-col :span="12">
      <el-descriptions v-if="detailData" :column="1" border>
        <el-descriptions-item label="人员类别">
          <dict-tag :options="dict.type.category2" :value="detailData.category"/>
        </el-descriptions-item>
        <el-descriptions-item label="识别相似度">{{ detailData.score }}</el-descriptions-item>
        <!-- <el-descriptions-item label="设备ID">{{ detailData.deviceId }}</el-descriptions-item> -->
        <el-descriptions-item label="设备端人员ID">{{ detailData.pid }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ detailData.idCard }}</el-descriptions-item>
        <!-- <el-descriptions-item label="创建人">{{ detailData.createBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detailData.updateBy }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item> -->
        <el-descriptions-item label="位置">{{ detailData.location }}</el-descriptions-item>
        <el-descriptions-item label="其他信息">{{ detailData.otherInfo }}</el-descriptions-item>
      </el-descriptions>
    </el-col>
  </el-row>

  <!-- 底部全宽内容 -->
  <div style="margin-top: 20px">
    <el-descriptions v-if="detailData" :column="1" border>
      <el-descriptions-item label="人脸图">
        <image-preview :src="detailData.jpegUrlFace" :width="100" :height="100"/>
      </el-descriptions-item>
    </el-descriptions>
  </div>

  <div slot="footer" class="dialog-footer">
    <el-button @click="detailDialogVisible = false">关 闭</el-button>
  </div>
</el-dialog>

<!-- 人员入库弹窗 - 优化版 -->
<el-dialog
  :title="'人员入库'"
  :visible.sync="addPersonDialogVisible"
  width="750px"
  append-to-body
  :close-on-click-modal="false"
>
  <el-form
    ref="addPersonForm"
    :model="addPersonForm"
    :rules="addPersonRules"
    label-width="100px"
    label-position="top"
  >
    <el-row :gutter="20">
      <!-- 左侧基本信息列 -->
      <el-col :span="12">
        <el-form-item label="身份信息" prop="name">
          <el-input v-model="addPersonForm.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="人员类别" prop="category">
          <el-select
            v-model="addPersonForm.category"
            placeholder="请选择人员类别"
            style="width:100%"
          >
            <el-option
              v-for="dict in dict.type.category"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

<!-- 修改后的入库弹窗性别字段 -->
<el-form-item label="性别" prop="gender">
  <el-radio-group v-model="addPersonForm.gender">
    <el-radio
      v-for="dict in dict.type.gender"
      :key="dict.value"
      :label="parseInt(dict.value)"
    >{{dict.label}}</el-radio>
  </el-radio-group>
</el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-select v-model="addPersonForm.age" placeholder="请选择年龄" style="width:100%">
            <el-option
              v-for="age in ageOptions"
              :key="age"
              :label="age"
              :value="age">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门/职位" prop="department">
          <el-input v-model="addPersonForm.department" placeholder="请输入部门/职位" />
        </el-form-item>

        <el-form-item label="工号" prop="workId">
          <el-input v-model="addPersonForm.workId" placeholder="请输入工号" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input
            v-model="addPersonForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>

      </el-col>

      <!-- 右侧联系信息列 -->
      <el-col :span="12">
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="addPersonForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="证件信息">
          <el-input
            v-model="addPersonForm.idCardNo"
            placeholder="请输入身份证号"
            style="margin-bottom:10px"
          />
          <el-input v-model="addPersonForm.icCardNo" placeholder="请输入IC卡号" />
        </el-form-item>

        <el-form-item label="设备关联" prop="deviceIds">
          <el-select
            v-model="addPersonForm.deviceIds"
            multiple
            placeholder="请选择关联设备（可多选）"
            style="width:100%"
          >
            <el-option
              v-for="device in deviceOptions"
              :key="device.sn"
              :label="device.location"
              :value="device.sn"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="人员照片" prop="photo">
          <image-upload v-model="addPersonForm.photo" class="photo-uploader"
                    :limit="1"/>
          <div class="upload-tip">建议尺寸：300×400px，JPG/PNG格式</div>
        </el-form-item>


      </el-col>
    </el-row>
  </el-form>

  <div slot="footer" class="dialog-footer">
    <el-button @click="addPersonDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAddPersonForm">确 定</el-button>
  </div>
</el-dialog>
  </div>


</template>

<script>
import { listCapture, getCapture, delCapture, addCapture, updateCapture } from "@/api/student/capture/capture";
import { addPerson } from "@/api/student/person/person";
import { listDevice } from "@/api/student/device/device";
export default {
  name: "Capture",
  dicts: ['category', 'gender', 'category2'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人脸抓拍记录表格数据
      captureList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 删除标志(0存在，1删除)时间范围
      daterangeTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null,
        name: null,
        age: null,
        gender: null,
        icCard: null,
        workId: null,
        phone: null,
        department: null,
        category: null,
        idCard: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 设备列表选项
      deviceOptions: [],
      detailDialogVisible: false,
      detailData: null,
      addPersonDialogVisible: false,
      addPersonForm: {
        deviceId: null,
        deviceIds: [],
        name: '',
        category: '',
        gender: '',
        age: null,
        department: '',
        workStatus: null,
        phone: '',
        idCardNo: '',
        workId: '',
        icCardNo: '',
        remark: '',
        photo: '',
        lastAppearTime: null,
      },
      // 入库表单校验规则
      addPersonRules: {
        deviceIds: [
          { required: true, message: "请至少选择一个设备", trigger: "change" },
          { type: 'array', min: 1, message: '请至少选择一个设备', trigger: 'change' }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        photo: [
          { required: true, message: "人员照片不能为空", trigger: "change" }
        ],
        age: [
          { required: true, message: "请选择年龄", trigger: "change" }
        ]
      },
      ageOptions: [],
    };
  },
  created() {
    this.getList();
    this.getDeviceList(); // 获取设备列表
    this.generateAgeOptions(); // 新增：生成年龄选项
  },
  methods: {
    /** 获取设备列表 */
    getDeviceList() {
      listDevice({
        pageNum: 1,
        pageSize: 1000 // 获取足够多的设备
      }).then(response => {
        this.deviceOptions = response.rows;
      });
    },
    /** 查询人脸抓拍记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeTime && '' != this.daterangeTime) {
        this.queryParams.params["beginTime"] = this.daterangeTime[0];
        this.queryParams.params["endTime"] = this.daterangeTime[1];
      }
      listCapture(this.queryParams).then(response => {
        this.captureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        time: null,
        sn: null,
        name: null,
        age: null,
        gender: null,
        icCard: null,
        workId: null,
        phone: null,
        department: null,
        otherInfo: null,
        category: null,
        score: null,
        helmet: null,
        smoke: null,
        handed: null,
        deviceId: null,
        pid: null,
        idCard: null,
        express: null,
        jpegUrlFace: null,
        jpegUrlBody: null,
        jpegUrlFrame: null,
        jpegUrlRcg: null,
        location: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人脸抓拍记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCapture(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改人脸抓拍记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCapture(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCapture(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除人脸抓拍记录编号为"' + ids + '"的数据项？').then(function() {
        return delCapture(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('student/capture/capture/export', {
        ...this.queryParams
      }, `capture_${new Date().getTime()}.xlsx`)
    },
    showDetail(row) {
      this.detailData = row;
      this.detailDialogVisible = true;
    },
    /** 打开入库表单弹窗 */
    showAddPersonDialog(row) {
      this.addPersonForm = {
        deviceId: row.deviceId,
        deviceIds: row.deviceId ? [row.deviceId] : [],
        name: row.name,
        category: 4,
        gender: row.gender,
        age: row.age,
        department: row.department,
        workStatus: null,
        phone: row.phone,
        idCardNo: row.idCard,
        workId: row.workId,
        icCardNo: row.icCard,
        remark: row.otherInfo || '',
        photo: row.jpegUrlFace,
        lastAppearTime: null,
      };
      this.addPersonDialogVisible = true;
    },
    /** 入库表单提交 */
    submitAddPersonForm() {
      this.$refs.addPersonForm.validate(valid => {
        if (valid) {
          if (!this.addPersonForm.deviceIds || this.addPersonForm.deviceIds.length === 0) {
            this.$modal.msgWarning("请至少选择一个设备");
            return;
          }
          this.addPersonForm.deviceId = this.addPersonForm.deviceIds[0];
          this.handleAddPerson(this.addPersonForm);
        }
      });
    },
    /** 入库方法，接收表单数据 */
    handleAddPerson(person) {
      addPerson(person).then(res => {
        if (res.code === 200) {
          this.$modal.msgSuccess("入库成功");
          this.addPersonDialogVisible = false;
        } else {
          this.$modal.msgError(res.msg || "入库失败");
        }
      }).catch(error => {
        console.error("入库失败", error);
        // 特殊处理设备为空的错误
        if (error.response && error.response.data && error.response.data.msg.includes("请至少选择一个设备")) {
          this.$modal.msgWarning("请至少选择一个设备");
        } else {
          this.$modal.msgError("入库失败: " + (error.response?.data?.msg || error.message || "未知错误"));
        }
      });
    },
    generateAgeOptions() {
      const ages = [];
      for (let i = 1; i <= 100; i++) {
        ages.push(i);
      }
      this.ageOptions = ages;
    },
  }
};
</script>

<style scoped>
.photo-uploader {
  width: 100%;
}
.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}
/* 下拉选择框样式优化 */
.el-select {
  width: 100%;
}
.el-form-item {
  margin-bottom: 18px;
}
</style>
